#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
import threading
import time
import random
from typing import Optional

from nacos_py import NacosService, NacosClient

NACOS_ENABLE = True

SERVER_ADDRESSES = "http://localhost:8848"
NAMESPACE = "public"
CLIENT: Optional[NacosClient] = None
SERVICE_NAME = "backend"

NAME = "nacos"  # Nacos用户名
PWD = "nacos"  # Nacos密码

from dotenv import load_dotenv

load_dotenv()
ADDRESS = os.getenv("ADDRESS")
PORT = os.getenv("PORT")

def heartbeat():
    while True:
        CLIENT.send_heartbeat("DEFAULT_GROUP@@" + SERVICE_NAME, os.getenv("ADDRESS"), os.getenv("PORT"))
        time.sleep(3)

if NACOS_ENABLE:
    CLIENT = NacosClient(SERVER_ADDRESSES, namespace=NAMESPACE, username=NAME, password=PWD)
    NacosService(SERVICE_NAME, CLIENT).register(ADDRESS, PORT)
    heart = threading.Thread(target=heartbeat, daemon=True)
    heart.start()

def get_service(service_name):
    instances = CLIENT.list_naming_instance(service_name, namespace_id=NAMESPACE, healthy_only=True)
    if len(instances["hosts"][0]) == 0:
        raise Exception(f"服务调用异常:没有找到指定服务-{service_name}")
    # 负载均衡
    host = random.choice(instances["hosts"])
    return host["ip"], host["port"]



def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    from django.core.management.commands.runserver import Command as Runserver

    Runserver.default_addr = ADDRESS
    Runserver.default_port = PORT
    main()
